﻿using Sharp.DataTransferObject;
using Sharp.Domain.PlatformBoundedContext.OAuthModule;
using Sharp.Domain.Repositories;
using Sharp.ServiceContracts;
using System;

namespace Sharp.Application.OAuth
{
    public class OAuthServiceImpl : ApplicationService, IOAuthService
    {
        private readonly IAuthorizationDataRepository _authorizationDataRepository;
        public OAuthServiceImpl(IRepositoryContext context,
            IAuthorizationDataRepository authorizationDataRepository) : base(context)
        {
            _authorizationDataRepository = authorizationDataRepository;
        }

        public AuthorizationDTO GetTicketValue(string token)
        {
            var tokenValue = _authorizationDataRepository.Get(x => x.Token == token).To<AuthorizationDTO>();

            return tokenValue;
        }

        public bool RemoveOldTicket(AuthorizationDTO grantData)
        {
            if (grantData.Token.IsNullOrEmpty())
            {
                return false;
            }
            var data = _authorizationDataRepository.Get(x => x.Token == grantData.Token);
            if (data != null)
            {
                _authorizationDataRepository.Remove(data);
                _authorizationDataRepository.Context.Commit();
                return true;
            }

            return false;
        }

        //public bool TryRemoveTicketValue(string token, out AuthorizationDTO tokenValue)
        //{
        //    var key = GetKey(token);

        //    DicTickets.TryRemove(key, out tokenValue);
        //    return true;
        //}

        public bool SetTicketValue(AuthorizationDTO tokenValue)
        {
            _authorizationDataRepository.Add(tokenValue.To<AuthorizationData>());
            _authorizationDataRepository.Context.Commit();
            return true;
        }


    }
}
